import React, {Component, PropTypes} from "react";
import {connect} from "react-redux";
import {Tree, Button, Modal, Spin} from "antd";
import {WeaRightMenu, WeaPopoverHrm, WeaScroll, WeaDialog} from "ecCom";
import {setResult} from "../actions/MyfavResultActions";
import {loadTree, selectTreeNode, saveTreeNode, destroyBrowser} from "../actions/FavouriteBrowserActions";
import {moveToAnotherDir} from "../actions/SysFavouriteActions";
import {closeDialog} from "../actions/FavouriteDialogActions";

const TreeNode = Tree.TreeNode;

class FavouriteBrowser extends Component {
    /**
     * 树节点加载
     * @param treeNode
     */
    loadTreeData = treeNode => {
        let {dispatch} = this.props;
        let treeKey = treeNode.props.eventKey;
        dispatch(loadTree(treeKey));
    }

    /**
     * 树节点选中
     * @param key
     * @param evt
     */
    onSelect = (key, evt) => {
        let {dispatch} = this.props;
        let dirId = "0";   //默认是根目录
        if (key.length > 0) {
            dirId = key[0];
        }

        if (dirId.indexOf("add") == -1 && dirId.indexOf("edit") == -1) {    //非编辑状态下
            /**
             * 记录下选中的节点
             */
            dispatch(selectTreeNode(dirId));
        }
    }

    /**
     * 保存目录
     * @param evt
     */
    saveFavourite = evt => {
        let {selectedKey, dispatch} = this.props;
        for (let key in this.refs) {
            let inputObj = this.refs[key];
            let value = inputObj.value;
            if (!value) {   //值为空
                Modal.error({content: "目录名称不能为空！"});
                inputObj.focus();
            } else {
                let parentid = selectedKey;
                let favname = value;
                let favdesc = "";
                let favorder = 0;
                dispatch(saveTreeNode({parentid, favname, favdesc, favorder}));
            }
            break;
        }
    }

    /**
     * 编辑框的回车事件处理
     * @param evt
     */
    handleOnKeyDown = evt => {
        let keyCode = evt.keyCode;
        if (keyCode == 13) {  //enter key
            this.saveFavourite(evt);
        }
    }

    /**
     * 关闭窗口
     */
    closeBrowserWin = () => {
        let {dispatch} = this.props;
        dispatch(closeDialog("2"));
        dispatch(destroyBrowser());
    }

    /**
     * 保存数据
     * @param evt
     */
    submitBrowserWin = (evt) => {
        let {selectedKey, moveids, dispatch} = this.props;
        if (!selectedKey) {   //没有选中目录
            Modal.error({
                content: "请选择一个目录！"
            });
        } else {
            dispatch(moveToAnotherDir(moveids.join(), selectedKey));
        }
    }

    renderComponent = data => data.map(item => {
        let {favid, favname, child, children, isinput} = item;
        let isLeaf = true;
        if (child == "1") {
            isLeaf = false;
            if (!!children) {
                return <TreeNode title={favname} key={favid}
                                 isLeaf={isLeaf}>{this.renderComponent(children)}</TreeNode>;
            }
        }

        if (isinput) {  //新增，或者编辑的节点，以input的形式展现
            favname = (
                <input type="text" ref="add_1" style={{"width": "80px"}}
                       onBlur={this.saveFavourite} onKeyDown={this.handleOnKeyDown}/>
            );
        }

        return <TreeNode title={favname} key={favid} isLeaf={isLeaf}/>;
    });

    /**
     * 当有节点编辑时，需要默认展开他的父节点
     * @param data
     * @param expandedKeys
     */
    getExpandedKeys = (data, expandedKeys) => {
        let that = this;
        data.forEach(function (item) {
            let {child, children, isinput, parentid} = item;
            if (child == "1") {
                if (!!children) {
                    that.getExpandedKeys(children, expandedKeys);
                }
            } else {
                if (isinput) {
                    expandedKeys.push(parentid);
                }
            }
        });
    }

    componentDidUpdate() {
        /**
         * 显示错误信息
         */
        let {dispatch} = this.props;
        let {success, msg} = this.props.myfavresult;
        if (success == "0") {
            if (!!msg) {
                Modal.error({content: msg});
            }
            dispatch(setResult("1"));
        }

        /**
         * 默认选中文本框
         */
        for (let key in this.refs) {
            this.refs[key].focus();
            break;
        }
    }

    render() {
        /**
         * 移动时，打开的收藏目录窗口信息
         */
        let {visible} = (this.props.dialog)["2"];
        let title = "收藏目录";
        let style = {width: 620, height: 500};
        let buttons = [
            (<Button onClick={this.submitBrowserWin}>确定</Button>),
            (<Button onClick={this.closeBrowserWin}>取消</Button>)
        ];
        let onCancel = this.closeBrowserWin;
        let params = {visible, title, style, buttons, onCancel};

        let {treeData, selectedKey, spinning, tip} = this.props;
        const treeNodes = this.renderComponent(treeData);
        //新增的编辑节点，默认展开父节点
        let expandedKeys = [];
        this.getExpandedKeys(treeData, expandedKeys);

        if (expandedKeys.length > 0) {
            return (
                <WeaDialog {...params}>
                    <Spin spinning={spinning} tip={tip} size="large" style={{"height": "100%"}}>
                        <div className="favourite-browser-container">
                            <WeaScroll className="sysfav-scroll-wrapper" typeClass="scrollbar-macosx"
                                       style={{"width": "100%"}}>
                                <Tree onSelect={this.onSelect}
                                      loadData={this.loadTreeData}
                                      showLine={true}
                                      selectedKeys={[selectedKey]}
                                      expandedKeys={expandedKeys}
                                      hasRadio={true}
                                      clickNodeExpandChildren={true}>
                                    {treeNodes}
                                </Tree>
                            </WeaScroll>
                        </div>
                    </Spin>
                </WeaDialog>
            );
        } else {
            return (
                <WeaDialog {...params}>
                    <Spin spinning={spinning} tip={tip} size="large">
                        <div className="favourite-browser-container">
                            <WeaScroll className="sysfav-scroll-wrapper" typeClass="scrollbar-macosx"
                                       style={{"width": "100%"}}>
                                <div className="favourite-browser-content">
                                    <Tree onSelect={this.onSelect}
                                          loadData={this.loadTreeData}
                                          showLine={true}
                                          selectedKeys={[selectedKey]}
                                          clickNodeExpandChildren={true}
                                          hasRadio={true}>
                                        {treeNodes}
                                    </Tree>
                                </div>
                            </WeaScroll>
                        </div>
                    </Spin>
                </WeaDialog>
            );
        }
    }
}

function mapStateToProps(state) {
    let {treeData, selectedKey, spinning, tip} = state.favouritebrowser;
    let myfavresult = state.myfavresult;
    let {moveids} = state.sysfavourite;
    let dialog = state.favouritedialog;
    return {treeData, selectedKey, myfavresult, dialog, moveids, spinning, tip};
}

export default connect(mapStateToProps)(FavouriteBrowser);

